<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>API Navigation</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pearForm.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/easyeditor.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/fangge-style.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pear-tree/dtree.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/doc-common.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/code.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/nav.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pear-tree/dtree.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pear-tree/font/dtreefont.css}"/>
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            font-size: 15px;
        }

        .dtree-nav-div cite {
            font-family: 'Roboto', sans-serif;
            font-size: 15px;
        }

        pre {
            background-color: #283142;
            color: white;
            font-size: 16px;
            font-family: Roboto, serif;
        }

        .layui-table td, .layui-table th {
            color: #0C0C0C;
            font-size: 15px;
        }

        .layui-table th {
            text-align: center;
        }

        tr:hover {
            cursor: pointer;
        }

        body {
            background-color: white;
        }

    </style>
</head>
<body>
<input id="projectId" type="hidden" th:value="${projectId}">

<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-md2">
            <div class="layui-row" style="margin-top: 20px">
                <div class="layui-col-md1"></div>
                <div class="layui-col-md8">
                    <input type="text" id="searchInput" name="title" required lay-verify="required" placeholder="关键字"
                           autocomplete="off"
                           class="layui-input">
                </div>
                <div class="layui-col-md2">
                    <button type="button" class="layui-btn" id="searchDocBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
                <div class="layui-col-md1"></div>
            </div>
            <div class="layui-row" style="margin-top: 20px">
                <ul id="dtreeTableContent" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-col-md10">
            <iframe id="apiDocFrame" src="" style="width: 100%;height: 900px" frameborder="no" border="0"
                    marginwidth="0"
                    marginheight="0"></iframe>
        </div>
    </div>
</div>

<form class="layui-form layui-form-pane" action="" id="create" style="display: none">
    <div class="layui-row" style="margin-top: 5%">
        <div class="layui-col-md12">
            <div id="parentResourceSelectDiv">
                <ul id='parentResourceSelect' class='dtree' data-id='0'></ul>
            </div>
            <input style="margin-top: 5%" type="text" id="name" name="name" required lay-verify="required"
                   placeholder="请输入名称"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
</form>

<script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/admin/js/jquery.js}"></script>
<script th:inline="javascript">
    var projectId = $("#projectId").val();
    var lay = null;

    // 根据readOnly进行动态渲染页面 屏蔽修改操作
    var readOnly = [[${readOnly}]];

    layui.config({
        base: '/restdoc/layui/lay/extends/'
    }).use(['table', 'util', 'layer', 'jquery', 'layedit', 'dtree'],
        function () {
            var dtree = layui.dtree;
            var $ = layui.jquery;
            var layer = layui.layer;
            util = layui.util;
            lay = layer;

            var dtreeData = null;

            function setDTreeData() {
                $.ajax({
                    type: 'GET',
                    url: "/restdoc/" + projectId + "/resource/dtree?at=REST_WEB",
                    async: false,
                    success: function (data) {
                        if (data['code'] === 0) {
                            dtreeData = data['data'];
                        } else {
                            layer.msg(data['msg']);
                        }
                    },
                    error: function () {
                        layer.msg("网络异常")
                    }
                });
            }

            setDTreeData();

            var dtreeOptions = {
                elem: "#dtreeTableContent",
                data: dtreeData,
                dataFormat: "list",
                initLevel: 1,
                skin: "zdy",
                iconfont: ["dtreefont", "layui-icon", "iconfont"],
                ficon: ["1", "-1"],
                iconfontStyle: {
                    fnode: {
                        node: {
                            open: "dtree-icon-xiangxia1",
                            close: "dtree-icon-xiangyou"
                        }
                    }
                },
                done: function (data, obj, first) {
                }
            };

            if (readOnly === null) {
                dtreeOptions['toolbar'] = true;
                dtreeOptions['toolbarShow'] = ['copyDoc', 'createResource', 'createApi', 'createWiki', 'modify', 'del'];
                dtreeOptions['toolbarExt'] = [
                    {
                        toolbarId: "copyDoc",
                        title: "复制文档",
                        handler: function (node, $div) {
                            copyDoc(node);
                        }
                    },
                    {
                        toolbarId: "modify",
                        title: "编辑",
                        handler: function (node, $div) {
                            editNode(node);
                        }
                    },
                    {
                        toolbarId: "createResource",
                        title: "新建目录",
                        handler: function (node, $div) {
                            commonToolHandler(node, node.nodeId, function (res, $obj, first) {
                                layer.open({
                                    type: 1,
                                    scrollbar: false,
                                    content: $('#create'),
                                    area: ['600px', '400px'],
                                    title: '新建目录',
                                    btn: ['确定', '取消'],
                                    yes: function (ix, layero) {
                                        var name = $("#name").val();
                                        if (name === "") {
                                            layer.msg("请输入名称");
                                        } else {
                                            var nid = dtree.selectVal("parentResourceSelect").parentResourceSelect_select_nodeId;
                                            if (nid === undefined) {
                                                layer.msg("请选择父级目录");
                                                return;
                                            }
                                            $.ajax({
                                                method: "POST",
                                                url: "/restdoc/" + projectId + "/resource",
                                                data: JSON.stringify({
                                                    "name": name,
                                                    "tag": "",
                                                    "pid": nid
                                                }),
                                                async: false,
                                                contentType: "application/json",
                                                success: function (res) {
                                                    resetCreateDiv();
                                                    if (res.code !== '200') layer.msg(res.message);
                                                }
                                            });
                                            layer.close(ix);
                                        }
                                    },
                                    end: function () {
                                        destroyTree();
                                    }
                                })
                            });
                        }
                    },
                    {
                        toolbarId: "createApi",
                        title: "新建API文档",
                        handler: function (node, $div) {
                            commonToolHandler(node, node.nodeId, function (res, $obj, first) {
                                createDoc("新建API文档", node, "API");
                            });
                        }
                    },
                    {
                        toolbarId: "createWiki",
                        title: "新建WIKI文档",
                        handler: function (node, $div) {
                            commonToolHandler(node, node.nodeId, function (res, $obj, first) {
                                createDoc("新建WIKI文档", node, "WIKI");
                            });
                        }
                    },
                    {
                        toolbarId: "del",
                        title: "删除",
                        handler: function (node, $div) {
                            deleteNode(node);
                        }
                    }
                ];
                dtreeOptions['toolbarFun'] = {
                    loadToolbarBefore: function (buttons, param, $div) {
                        if (nodeIsResource(param.nodeId)) {
                            buttons.copyDoc = "";
                            if (param.nodeId === 'root') {
                                buttons.del = "";
                                buttons.modify = "";
                            }
                        } else {
                            buttons.createResource = "";
                            buttons.createApi = "";
                            buttons.createWiki = "";
                        }
                        return buttons;
                    }
                };
            }

            var DemoTree = dtree.render(dtreeOptions);

            function editNode(node) {
                commonToolHandler(node, node.parentId, function () {
                    $("#name").val(node.context);
                    layer.open({
                        type: 1,
                        scrollbar: false,
                        content: $('#create'),
                        area: ['600px', '400px'],
                        title: '编辑',
                        btn: ['确定', '取消'],
                        yes: function (ix, layero) {
                            var url = nodeIsResource(node.nodeId) ? "/restdoc/resource" : "/restdoc/document/baseinfo";
                            $.ajax({
                                method: "PATCH",
                                url: url,
                                contentType: "application/json",
                                async: false,
                                data: JSON.stringify({
                                    name: $("#name").val(),
                                    id: node.nodeId,
                                    pid: dtree.selectVal("parentResourceSelect").parentResourceSelect_select_nodeId,
                                    order: 0
                                }),
                                success: function (res) {
                                    if (res.code === '200') {
                                        layer.msg('操作成功');
                                        reloadNavTree();
                                    } else {
                                        layer.msg(res.message);
                                    }
                                }
                            });
                            layer.close(ix);
                        },
                        end: function () {
                            destroyTree();
                        }
                    })
                })
            }

            function deleteNode(node) {
                layer.confirm('删除后不可恢复! 确认删除' + node.context + '?', {icon: 3, title: '提示'},
                    function (index) {
                        if (nodeIsResource(node.nodeId)) {
                            var hasChildren = false;
                            for (var i = 0; i < dtreeData.length; i++) {
                                if (dtreeData[i].parentId === node.nodeId) {
                                    hasChildren = true;
                                    break;
                                }
                            }
                            if (hasChildren) {
                                layer.alert("该目录下还存在文档，不可删除");
                                return;
                            } else {
                                $.ajax({
                                    method: "DELETE",
                                    url: "/restdoc/" + projectId + "/resource/" + node.nodeId,
                                    async: false,
                                    success: function (res) {
                                        if (res.code === '200') {
                                            layer.msg("操作成功");
                                            reloadNavTree();
                                        } else layer.msg(res.message);
                                    }
                                });
                            }
                        } else {
                            $.ajax({
                                method: "DELETE",
                                url: "/restdoc/document/" + node.nodeId,
                                async: false,
                                success: function (res) {
                                    if (res.code === '200') {
                                        if ($("#apiDocFrame").attr("src").includes(node.nodeId)) {
                                            layer.msg("操作成功");
                                            parent.location.reload();
                                        } else {
                                            reloadNavTree();
                                        }
                                    } else layer.msg(res.message);
                                }
                            });
                        }
                        layer.close(index);
                    });
            }

            function resetCreateDiv() {
                reloadNavTree();
                $("#name").val("");
            }


            function reloadNavTree() {
                setDTreeData();
                dtree.reload(DemoTree, {
                    data: dtreeData,
                    dataFormat: "list"
                })
            }

            function copyDoc(node) {
                commonToolHandler(node, node.parentId, function () {
                    $("#name").val(node.context);
                    layer.open({
                        type: 1,
                        scrollbar: false,
                        content: $('#create'),
                        area: ['600px', '400px'],
                        title: '拷贝文档',
                        btn: ['确定', '取消'],
                        yes: function (ix, layero) {
                            $.ajax({
                                method: "POST",
                                url: "/restdoc/document/copy",
                                contentType: "application/json",
                                data: JSON.stringify({
                                    name: $("#name").val(),
                                    resourceId: dtree.selectVal("parentResourceSelect").parentResourceSelect_select_nodeId,
                                    documentId: node.nodeId
                                }),
                                async: false,
                                success: function (res) {
                                    $("#name").val("");
                                }
                            });
                            layer.close(ix);
                            reloadNavTree();
                        },
                        end: function () {
                            destroyTree();
                        }
                    });
                })
            }

            function createDoc(windowTitle, node, docType) {
                layer.open({
                    type: 1,
                    scrollbar: false,
                    content: $('#create'),
                    area: ['600px', '400px'],
                    title: windowTitle,
                    btn: ['确定', '取消'],
                    yes: function (ix, layero) {
                        var name = $("#name").val();
                        if (name === "") {
                            layer.msg("请输入名称");
                        } else {
                            var nid = dtree.selectVal("parentResourceSelect").parentResourceSelect_select_nodeId;
                            if (nid === undefined) {
                                layer.msg("请选择目录");
                                return;
                            }
                            $.ajax({
                                method: "POST",
                                url: "/restdoc/document/emptydoc",
                                data: JSON.stringify({
                                    "name": name,
                                    "resourceId": nid,
                                    "projectId": projectId,
                                    "docType": docType
                                }),
                                async: false,
                                contentType: "application/json",
                                success: function (res) {
                                    if (res.code === '200') {
                                        resetCreateDiv();
                                        dtree.selectVal("dtreeTableContent", res.data);
                                        $("#apiDocFrame").attr("src", '/restdoc/' + projectId + '/document/' + res.data + '/view');
                                    } else {
                                        layer.msg(res.message);
                                    }
                                }
                            });
                            layer.close(ix);
                        }
                    },
                    end: function () {
                        destroyTree();
                    }
                })
            }

            function destroyTree() {
                $("#parentResourceSelectDiv").html("<ul id='parentResourceSelect' class='dtree' data-id='0'></ul>");
            }

            function commonToolHandler(node, initNodeId, doneFunc) {
                var resources = filterResources();
                hideSelectNavTree = dtree.renderSelect({
                    elem: "#parentResourceSelect",
                    width: "100%",
                    data: resources,
                    dataFormat: "list",
                    skin: "zdy",
                    iconfont: ["dtreefont", "layui-icon", "iconfont"],
                    ficon: ["1", "-1"],
                    iconfontStyle: {
                        fnode: {
                            node: {
                                open: "dtree-icon-xiangxia1",
                                close: "dtree-icon-xiangyou"
                            }
                        }
                    },
                    selectInitVal: initNodeId,
                    done: doneFunc
                });
            }

            function filterResources() {
                var resources = [];
                if (dtreeData !== null) {
                    for (var i = 0; i < dtreeData.length; i++) {
                        if (dtreeData[i].type === "RESOURCE") {
                            resources.push(dtreeData[i]);
                        }
                    }
                }
                return resources;
            }

            function searchNode() {
                var value = $("#searchInput").val();
                if (value) {
                    if (!DemoTree.searchNode(value)) layer.msg("该名称节点不存在！", {icon: 5});
                } else DemoTree.menubarMethod().refreshTree();  // 内置方法刷新树
            }

            $("#searchDocBtn").click(function () {
                searchNode();
            });

            $("#searchInput").bind('keypress', function (event) {
                if (event.keyCode == "13") {
                    searchNode();
                }
            });

            dtree.on("node('dtreeTableContent')", function (obj) {
                if (obj.param.leaf) {
                    if (!nodeIsResource(obj.param.nodeId)) {
                        $("#apiDocFrame").attr("src", '/restdoc/' + projectId + '/document/' + obj.param.nodeId + '/view');
                    }
                } else {
                    DemoTree.clickSpread(obj.dom);
                }
            });
            var docId = getFirstDocument(dtreeData);
            if (null != docId) {
                $("#apiDocFrame").attr("src", '/restdoc/' + projectId + '/document/' + docId + '/view');
            }

            function nodeIsResource(nodeId) {
                for (var i = 0; i < dtreeData.length; i++) {
                    if (dtreeData[i].id === nodeId) {
                        if (dtreeData[i].type == "WIKI" || dtreeData[i].type == "API") {
                            return false;
                        }
                        break;
                    }
                }
                return true;
            }
        });

    function getFirstDocument(array) {
        if (array == null || array.length === 0) return null;
        var length = array.length;
        var flag = 0;
        for (let i = 0; i < length; i++) {
            var node = array[i];
            if ("API" === node['type'] || "WIKI" === node['type']) {
                if (flag === 0) {
                    return node['id']
                }
            } else {
                var result = findFirstChildren(node);
                if (result != null) return result;
            }
        }
        return null;
    }

    function findFirstChildren(parentNode) {
        if (parentNode != null && parentNode['children'].length === 0) {
            return null;
        } else {
            var children = parentNode['children'];
            var length = children.length;

            for (let i = 0; i < length; i++) {
                if (children[i]['type'] === 'WIKI' || children[i]['type'] === 'API') {
                    return children[i]['id']
                } else {
                    var result = findFirstChildren(children[i]);
                    if (null != result) {
                        return result;
                    }
                }
            }
            return null;
        }
    }
</script>
</body>
</html>